package com.jy.appmarket.activity;

import java.util.ArrayList;
import java.util.List;

import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.LinearLayout;

import com.jy.appmarket.R;
import com.jy.appmarket.adapter.DeskTopAppAdapter;
import com.jy.appmarket.model.AppInfoModel;
import com.jy.appmarket.utils.LogUtil;
import com.jy.appmarket.utils.PackageUtils;
import com.jy.appmarket.utils.Prefs;
import com.jy.appmarket.utils.WidgetIconUtils;
import com.jy.appmarket.view.LoadingView;
import com.umeng.analytics.MobclickAgent;

public class DeskTopAppManagerActivity extends Activity implements
		LoadingView.OnClickListener, OnItemClickListener {

	public static final int REQUEST_CODE = 1001;
	private static final String TAG = "DeskTopAppManagerActivity";
	private GridView mGridView;
	private DeskTopAppAdapter mAdapter;
	private List<AppInfoModel> mList = new ArrayList<AppInfoModel>();
	private int mType;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_desktop_app_manager);
		getType();
		initView();
		getData();
	}

	private void getType() {
		Intent intent = getIntent();
		if (intent.hasExtra(WindowActivity.TYPE)) {
			mType = intent.getIntExtra(WindowActivity.TYPE, 1);
		} else {
			LogUtil.w(TAG, "unknown type");
			finish();
		}
	}

	private View.OnClickListener mButtonListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			if (mList == null || mList.size() == 0) {
				return;
			}

			StringBuilder sb = new StringBuilder();
			for (AppInfoModel app : mList) {
				if (app.isSelected()) {
					sb.append(app.getPackageName()).append("|");
				}
			}
			if (sb.length() > 0) {
				sb.deleteCharAt(sb.length() - 1);
			}
			LogUtil.d(TAG, sb.toString());
			if (mType == WidgetIconUtils.TYPE_TOOL_WIDGET) {
				Prefs.saveDesktopSoftware(DeskTopAppManagerActivity.this, sb.toString());
			} else if (mType == WidgetIconUtils.TYPE_GAME_WIDGET) {
				Prefs.saveDesktopGame(DeskTopAppManagerActivity.this, sb.toString());

			} else if (mType == WidgetIconUtils.TYPE_ENTERTAINMENT_WIDGET) {
				Prefs.saveDesktopEntertainment(DeskTopAppManagerActivity.this, sb.toString());
			} else {
				LogUtil.w(TAG, "invalid type");
			}
			setResult(Activity.RESULT_OK);
			finish();
		}
	};

	private void initView() {
		ActionBar actionBar = getActionBar();
		actionBar.setTitle(R.string.select_app);
		actionBar.setDisplayUseLogoEnabled(false);
		actionBar.setDisplayShowHomeEnabled(false);
		actionBar.setDisplayHomeAsUpEnabled(true);
		mGridView = findViewById(R.id.desktop_app_gridiew);
		mGridView.setOnItemClickListener(this);
		findViewById(R.id.cancel).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				DeskTopAppManagerActivity.this.finish();
			}
		});
		findViewById(R.id.confirm).setOnClickListener(mButtonListener);
	}

	private void showLoading(boolean loading) {
		LoadingView loadingview = findViewById(R.id.loading_view_layout);
		View contentview = findViewById(R.id.desktop_app_content);

		if (loading) {
			loadingview.setVisibility(View.VISIBLE);
			loadingview.setOnClickListener(this);
			loadingview.showWaitView(getString(R.string.ptr1_loading_wait));
			//loadingview.setImage(0);
			contentview.setVisibility(View.GONE);
		} else {
			loadingview.setVisibility(View.GONE);
			contentview.setVisibility(View.VISIBLE);
		}
	}

	private void showEmpty() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				LoadingView loadingview = findViewById(R.id.loading_view_layout);
				View contentview = findViewById(R.id.desktop_app_content);
				loadingview.setVisibility(View.VISIBLE);
				loadingview.setOnClickListener(DeskTopAppManagerActivity.this);
				loadingview.showWaitView(getString(R.string.ptr1_loading_wait));
				//loadingview.setImage(0);
				contentview.setVisibility(View.GONE);
			}
		});

	}

	private void updateUI() {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				mAdapter = new DeskTopAppAdapter(DeskTopAppManagerActivity.this);
				mAdapter.setList(mList);
				mGridView.setAdapter(mAdapter);
				showLoading(false);
			}
		});
	}

	private void getData() {
		showLoading(true);
		new Thread() {
			public void run() {
				List<AppInfoModel> list = PackageUtils.getInstalledUserPackages(
						DeskTopAppManagerActivity.this, true);
				if (list == null || list.size() == 0) {
					showEmpty();
				} else {
					for (AppInfoModel app : list) {
						if (getPackageName().equals(app.getPackageName())) {
							list.remove(app);
							break;
						}
					}

					String[] ss = WidgetIconUtils.getInstance().getUserSavedPackages(
							DeskTopAppManagerActivity.this, mType);
					List<AppInfoModel> selectList = new ArrayList<AppInfoModel>();
					List<AppInfoModel> unselectList = new ArrayList<AppInfoModel>();
					mList.clear();
					if (ss != null && ss.length != 0) {
						List<String> pkgNameList = new ArrayList<String>();
						for (String s : ss) {
							pkgNameList.add(s);
						}
						for (AppInfoModel app : list) {
							if (pkgNameList.contains(app.getPackageName())) {
								app.setSelected(true);
								selectList.add(app);
							} else {
								app.setSelected(false);
								unselectList.add(app);
							}
						}
						mList.addAll(selectList);
						mList.addAll(unselectList);
					} else {
						mList.addAll(list);
					}

					if (mList.size() == 0) {
						showEmpty();
					} else {
						updateUI();
					}
				}
			}
        }.start();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		MobclickAgent.onPause(this);
	}


	@Override
	public void onLoadingViewClick(View view) {
		// nothing to do
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (mAdapter != null) {
			AppInfoModel app = mList.get(position);
			app.setSelected(!app.isSelected());
			mAdapter.notifyDataSetChanged();
		}
	}
}
